package com.college.common.utils.security;

import com.alibaba.fastjson2.JSONObject;
import com.college.common.utils.log.LogPrintUtils;
import com.college.common.utils.sign.MapUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.*;


@Slf4j
public class AESUtils {

    public static void main(String[] args) {
        // String aes = AESUtils.Encrypt128("{\"realPhone\":\"13521235822\",\"realName\":\"小陈\",\"idCardNo\":\"362524198609182536\",\"checkNo\":\"a5dd5ece3b7541f5a243c4e7a702f696\",\"accumulationFund\":\"无\",\"businessInsurance\":\"无\",\"businessOwners\":\"无\",\"carProperty\":\"有\",\"creditSituation\":\"无\",\"houseProperty\":\"有\",\"loanLimit\":\"200000\",\"loanLongTime\":6,\"location\":\"福建省,厦门市\",\"monthlyIncome\":8000,\"openJdbt\":\"无\",\"openRedit\":\"无\",\"openSpendBai\":\"无\",\"sex\":0,\"age\":29,\"socialInsurance\":\"有\",\"zmScore\":\"0-599\",\"province\":\"江苏省\"}", "1234567890123456");
        String aes = AESUtils.Encrypt128("{\"md5Phone\":\"ebfbcc2d28129a59f4963c6f9800e3eb\",\"realName\":\"小陈\",\"idCardNo\":\"362524198609182536\",\"checkNo\":\"d90f9624c13a4927a225c30b802a8988\",\"accumulationFund\":\"无\",\"businessInsurance\":\"无\",\"businessOwners\":\"无\",\"carProperty\":\"有\",\"creditSituation\":\"无\",\"houseProperty\":\"有\",\"loanLimit\":\"200000\",\"loanLongTime\":6,\"location\":\"福建省,厦门市\",\"monthlyIncome\":8000,\"openJdbt\":\"无\",\"openRedit\":\"无\",\"openSpendBai\":\"无\",\"sex\":0,\"age\":29,\"socialInsurance\":\"有\",\"zmScore\":\"0-599\",\"province\":\"江苏省\"}", "1234567890123456");
        // String aes = AESUtils.Encrypt128("{\"md5Phone\":\"0d602a6788d27b3a7a9b5641b250c522\",\"accumulationFund\":\"有\",\"idCardNo\":\"511028199511245711\",\"sex\":1,\"zmScore\":\"700以上\",\"carProperty\":\"有\",\"realName\":\"周五正\",\"openSpendBai\":\"有\",\"openJdbt\":\"有\",\"businessOwners\":\"无\",\"checkNo\":\"3fefc67a9ba543de963a9075e632f185\",\"loanLimit\":10,\"businessInsurance\":\"有\",\"houseProperty\":\"有\",\"location\":\"西藏省份,拉萨市\",\"age\":28,\"creditSituation\":\"有\",\"socialInsurance\":\"有\",\"openRedit\":\"有\"}", "1234567890123456");
        // String aes = AESUtils.Encrypt128("{\"md5Phone\":\"48707d5ca3e7970e460206a3e17450b1\"}", "1234567890123456");
        System.out.println(aes);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("channelId", "319");
        jsonObject.put("timestamp", "2023-07-20 00:00:00");
        jsonObject.put("data", aes);
        String signString = MapUtils.getSign(jsonObject, "=", "&");
        System.out.println("signString:"+signString);
        System.out.println(DigestUtils.md5Hex(signString + "1234567890123456"));
        // System.out.println(Decrypt128("cPZApkbiisY46OLamaB+EnbVvdRSosKsSTsctV/STcGtbv4FIw8M+PtHshbLXG9VtAMcKkT9cMZ+eIHAtfSW6wck2vrfazvd7wA1Gs4d2MlmfPVcEoKpVnv2cAp9/rio05mI8conoPoMb+ge8Z0dsZDqr/r8dRjb5WKC3HJia7GaxbRLZ5Qs/8EefH4JpZ8YQg2T5UBj5wD5mLV6m94Nmy4ULBKBUMpTv+DOjSath6jl9SZDhca1EYBPrd5m99clKEAi44GwocwOG4ZOqFWZ++G273AUHa9EG4HRRhqH4gCHPO/NmMbzgKIel7xl7wVBzUnyu37oOPgE/kkj825TCTZVdmxGPk/JgVC256hLuu9RQDs0gI4N+XyQdEdPwuS39CIdy1QT/FcJ/udLGYQ5CJa4Vjwus8JmmMmTgV2Lb0SlTl/x4UHt5u8jCNJUfViQPW+1S8auX63/X5LT3aj/WQI/jsoHdd5EbyRS8gaXIivO1jExFmM75FKJtQH/5qJca1/SkrobmDY1eLVly9jSIlls4TInonGYgu4rAcFWkdIOl0FQoRnkFwKkPwrxn+35c5/nC1TvFHETsni2E8nelA==", "1234567890123456"));
    }
    /**
     * 015 ： AES-128-ECB（加密算法）
     * key = "oxAvmnw6cqcsdRLT";
     */
    public static String Encrypt128(String sSrc, String sKey) {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        byte[] raw;
        try {
            raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            return new Base64().encodeToString(encrypted);// 此处使用BASE64做转码功能，同时能起到2次加密的作用。
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    public static String Encrypt128ByHex(String sSrc, String sKey) {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        byte[] raw;
        try {
            raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            return bytesToHex(encrypted);// 此处使用BASE64做转码功能，同时能起到2次加密的作用。
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 字节数组转Hex
     *
     * @param bytes 字节数组
     * @return Hex
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        if (bytes != null && bytes.length > 0) {
            for (int i = 0; i < bytes.length; i++) {
                String hex = byteToHex(bytes[i]);
                sb.append(hex);
            }
        }
        return sb.toString();
    }

    /**
     * Byte字节转Hex
     *
     * @param b 字节
     * @return Hex
     */
    public static String byteToHex(byte b) {
        String hexString = Integer.toHexString(b & 0xFF);
        // 由于十六进制是由0~9、A~F来表示1~16，所以如果Byte转换成Hex后如果是<16,就会是一个字符（比如A=10），通常是使用两个字符来表示16进制位的,
        // 假如一个字符的话，遇到字符串11，这到底是1个字节，还是1和1两个字节，容易混淆，如果是补0，那么1和1补充后就是0101，11就表示纯粹的11
        if (hexString.length() < 2) {
            hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
        }
        return hexString.toUpperCase();
    }


    /**
     * AES-ECB算法128位解密
     *
     * @param encrypMsg
     * @return
     */
    public static String Decrypt128(String encrypMsg, String aesKey) {
        try {
            Cipher cipher = Cipher.getInstance("AES");
            SecretKeySpec keySpec = new SecretKeySpec(aesKey.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] encrypted1 = new Base64().decode(encrypMsg);
            byte[] decbbdt = cipher.doFinal(encrypted1);
            return new String(decbbdt, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

/*    public static void main(String[] args) throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, NoSuchProviderException, InvalidKeyException {
        String content = "test中文";

// 构建
        AES aes = SecureUtil.aes("5lvNIA1Kmchq2gu3C9P5g+rttvQXq3lh".getBytes());
// 加密
        byte[] encrypt = aes.encrypt(content);
// 解密
        byte[] decrypt = aes.decrypt(encrypt);
        System.out.println(new Base64().encodeToString(encrypt));
        //System.out.println(Encrypt_256("1234567890", "5lvNIA1Kmchq2gu3C9P5g+rttvQXq3lh"));

    }*/

    /**
     * 015 ： AES-256-ECB（加密算法）
     */
    public static String Encrypt_256(String sSrc, String sKey) {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
//        if (sKey.length() != 16) {
//            System.out.print("Key长度不是16位");
//            return null;
//        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128); // 192 and 256 bits may not be available
            SecretKeySpec aes = new SecretKeySpec(sKey.getBytes(), "AES");
            // 创建密码器
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            // 初始化
            cipher.init(Cipher.ENCRYPT_MODE, aes);
            byte[] bytes = cipher.doFinal(sSrc.getBytes());
            return new Base64().encodeToString(bytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 加密方法
     * AES-128-CBC
     *
     * @param data 要加密的数据
     * @param key  加密key
     * @param iv   加密iv
     * @return 加密的结果
     * @throws Exception
     */
    public static String encryptAES_128_CBC(String data, String key, String iv) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式"
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);

            return new Base64().encodeToString(encrypted);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String aesCBCencrypt(String data , String key , String vi){
        try {
            // 将AES密钥转换为SecretKeySpec对象
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
            // 将AES初始化向量转换为IvParameterSpec对象
            IvParameterSpec ivParameterSpec = new IvParameterSpec(vi.getBytes());
            // 根据加密算法获取加密器
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            // 初始化加密器，设置加密模式、密钥和初始化向量
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            // 加密数据
            byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            // 对加密后的数据使用Base64编码
            return java.util.Base64.getEncoder().encodeToString(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static String aesCBCdecrypt(String encryptedData  , String key , String vi) {
        try {
            // 将AES密钥转换为SecretKeySpec对象
            SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
            // 将AES初始化向量转换为IvParameterSpec对象
            IvParameterSpec ivParameterSpec = new IvParameterSpec(vi.getBytes());
            // 根据加密算法获取解密器
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            // 初始化解密器，设置解密模式、密钥和初始化向量
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            // 对加密后的数据使用Base64解码
            byte[] decodedData = java.util.Base64.getDecoder().decode(encryptedData);
            // 解密数据
            byte[] decryptedData = cipher.doFinal(decodedData);
            // 返回解密后的数据
            return new String(decryptedData, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 加密方法
     * AES-128-CBC
     *
     * @param data 要加密的数据 PKCS5Padding
     * @param key  加密key
     * @param iv   加密iv
     * @return 加密的结果
     * @throws Exception
     */
    public static String encryptAES_128_CBC_PKCS5Padding(String data, String key, String iv) {
        return encryptAES_128_CBC_PKCS5Padding_module(data, key, iv, null);
    }

    public static String encryptAES_128_CBC_PKCS5Padding_module(String data, String key, String iv, String codeFormat) {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
            byte[] dataBytes;
            if (StringUtils.isNotBlank(codeFormat)) {
                dataBytes = data.getBytes(codeFormat);
            } else {
                dataBytes = data.getBytes();
            }
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(dataBytes);

            return new Base64().encodeToString(encrypted);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String decryptAES_128_CBC_PKCS5Padding(String data, String key, String iv) {
        try {
            byte[] encrypted1 = new Base64().decode(data);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解密方法
     * AES-128-CBC
     *
     * @param data 要解密的数据
     * @param key  解密key
     * @param iv   解密iv
     * @return 解密的结果
     * @throws Exception
     */
    public static String desEncryptAES_128_CBC(String data, String key, String iv) {
        try {
            byte[] encrypted1 = new Base64().decode(data);

            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encryptAES(String data, String key, String iv) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            int blockSize = cipher.getBlockSize();
            data = replaceAllSpecial(data);
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;

            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }

            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            if (iv != null) {
                IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
                cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            } else {
                cipher.init(Cipher.ENCRYPT_MODE, keyspec);
            }

            byte[] encrypted = cipher.doFinal(plaintext);
            return java.util.Base64.getEncoder().encodeToString(encrypted);

        } catch (Exception e) {
            return null;
        }
    }

    public static String encryptAES_128_CBC_PKCS5Padding_Base64(String data, String key) {
        byte[] dataByteArray = data.getBytes(StandardCharsets.UTF_8);
        byte[] keyByteArray = java.util.Base64.getDecoder().decode(key);
        try {
            SecretKeySpec secretKey = new SecretKeySpec(keyByteArray, "AES");
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ivspec = new IvParameterSpec(keyByteArray);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
            byte[] valueByte = cipher.doFinal(dataByteArray);
            return java.util.Base64.getEncoder().encodeToString(valueByte);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String decryptAES_128_CBC_PKCS5Padding_Base64(String data, String key) {
        byte[] originalData = java.util.Base64.getDecoder().decode(data.getBytes());
        byte[] keyByteArray = java.util.Base64.getDecoder().decode(key);
        try {
            SecretKeySpec secretKey = new SecretKeySpec(keyByteArray, "AES");
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ivspec = new IvParameterSpec(keyByteArray);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec);
            byte[] valueByte = cipher.doFinal(originalData);
            return new String(valueByte,StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 解密
     *
     * @param data 密文
     * @param key  密钥，长度16
     * @param iv   偏移量，长度16
     * @return 明文
     * @author miracle.qu
     */
    public static String decryptAES(String data, String key, String iv) {
        try {
            data = replaceAllSpecial(data);
            byte[] encrypted1 = java.util.Base64.getDecoder().decode(data);

            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            if (iv != null) {
                IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
                cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            } else {
                cipher.init(Cipher.DECRYPT_MODE, keyspec);
            }

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original);
            return originalString.trim();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 解密
     *
     * @param contentString 已加密需解密的字符串
     * @param password      解密秘钥
     * @return
     */
    public static String decrypt(String contentString, String password) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());
            kgen.init(128, random);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
            byte[] decryptBytes = cipher.doFinal(decoder.decodeBuffer(contentString));

            return new String(decryptBytes);
        } catch (Exception e) {
            LogPrintUtils.info("aes解密失败，具体信息：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 基于password生成密钥加密
     *
     * @param content  需要加密的内容
     * @param password 加密密码，用于作为密钥的seed
     * @return AES 加密后的2进制字节码
     */
    public static String encryptAesEcbSHA1PRNG(String content, String password) {
        try {
            // 生成密钥
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes());
            keyGen.init(128, secureRandom);
            SecretKey secretKey = keyGen.generateKey();
            // 创建密码器
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            // 初始化
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            // 加密
            byte[] encryptByteData = cipher.doFinal(byteContent);

            BASE64Encoder encoder = new BASE64Encoder();
            String result = encoder.encode(encryptByteData);
            // 去掉签名中的换行符
            result = result.replaceAll("\r\n", "").replaceAll("\n", "");
            return result;
        } catch (Exception e) {
            log.error("加密失败: " + e);
        }
        return null;
    }

    // 把单\号换成空字符串
    public static String replaceAllSpecial(String s) {
        return s.replaceAll("\\\\", "");
    }

    public static String encryptAesCbc(String srcDataStr, String keyStr, String ivStr) {
        try {
            byte[] iv = new byte[16];
            System.arraycopy(ivStr.getBytes("UTF-8"), 0, iv, 0, iv.length);
            return removeRNT(Base64.encodeBase64String(encrypt(srcDataStr.getBytes("UTF-8"), keyStr.getBytes("UTF-8"), iv)));

        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] encrypt(byte[] srcData, byte[] key, byte[] iv) {
        try {
            Cipher.getMaxAllowedKeyLength("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
            return cipher.doFinal(srcData);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidAlgorithmParameterException e) {
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    private static String removeRNT(String originalStr) {
        if (originalStr == null || originalStr.isEmpty()) {
            return originalStr;
        }
        return originalStr.replaceAll("[\t\n\r]", "");
    }

    // 加密
    public static String encryptAESCBC256(String text, String key, byte[] iv) {
        String algorithm = "AES";
        String transform = "AES/CBC/PKCS5Padding";//
        Cipher cipher = null;
        String result = "";
        try {
            byte[] keyarr = autoKey(getSHA256Str(key));
            SecretKeySpec keySpec = new SecretKeySpec(keyarr, algorithm);
            cipher = Cipher.getInstance(transform);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
            byte[] cipherData = cipher.doFinal(text.getBytes("UTF-8"));
            result = Base64.encodeBase64String(cipherData);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(result);
        return result;
    }

    // 长度不够处理
    public static byte[] autoKey(byte[] key) {
        byte[] bytes = new byte[32];
        for (int i = 0; i < 32; i++) {
            bytes[i] = 0;
        }
        if (key.length >= 32) {
            System.arraycopy(key, 0, bytes, 0, 32);
        } else {
            System.arraycopy(key, 0, bytes, 0, key.length);
        }
        return bytes;
    }

    // 256加密
    public static byte[] getSHA256Str(String str) {
        MessageDigest messageDigest;
        byte[] encdeStr = null;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            encdeStr = messageDigest.digest(str.getBytes("UTF-8"));
            // encdeStr = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encdeStr;
    }


}
